package oa.hleast.xswl.utils;

import cn.hutool.poi.word.WordUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author
 */
@Slf4j
public class PoiUtils {

    public static void createWord(Map<String,Object> dataMap, List<String> tagNameList, String templatePath, HttpServletResponse response,String exportPath) throws Exception{
        log.info("dataMap = {} , tagNameList = {}, templatePath = {}",dataMap, tagNameList, templatePath);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder().build();
        for (String tagName : tagNameList) {
            config.customPolicy(tagName,policy);
        }

        XWPFTemplate template = XWPFTemplate.compile(WordUtil.class.getClassLoader().getResourceAsStream(templatePath), config).render(dataMap);
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-world");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(exportPath, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".docx");
        try (OutputStream out = response.getOutputStream())
        {
            // 将数据写出去
            template.write(out);
        } catch (Exception e)
        {
            e.printStackTrace();
            log.info("数据写出失败");
        }
    }
}




